import ScrollBarLayout from '@/components/ScrollBarLayout';
import Cls from 'classnames';
import { useContext, useEffect, useState } from 'react';
import { ChangeControllerContext } from '../common/useOAContext';
import { Form, Select, Spin, Tooltip, TreeSelect, message, Button } from 'antd';
import { DescriptionsType, useDescriptionsType } from '@/components/DescriptionsType';
import { downloadTemplate, getFileNameNotType, getLoadMapList, getTenantID, removeDateHmsStr, splitFileUrl } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import MyIcon from '@/components/MyIcon';
import { formatDecimal } from '../../Acommon';
import { getFlowOrgTreeByOrgIDService, getUserDataList } from '@/services/BaseLayout';
import { claimTypeList, damageTypeList, repealTypeList, riskLevelList } from '../mconfig/UpdateConfig';
import DetailInfoTableList from './DetailInfoTableList';
import { TypographyTitle } from '@/components/Typography/TypographyTitle';
import moment from 'moment';
import { getBaseUrl } from '@/services/urlconst';
import { readReadShowFileService } from '@/services/BaseLayout';
import { EyeOutlined } from '@ant-design/icons';

export const DetailInfoCenterViewMainOA: React.FC = () => {
  /** 引入上下文 */
  const { styleFixCls, infoObj } = useContext(ChangeControllerContext);

  const [isPass, setIsPass] = useState<boolean>(false); // 是否通过线下审批

  /** 轻阅读预览 */
  const { readReadShowFileRun } = readReadShowFileService();

  /**轻阅读预览 */
  const onOpenReadOfdWord = (fieldUrl: string) => {
    readReadShowFileRun({ fieldPath: `${getBaseUrl()}${fieldUrl}` });
  };

  /**  获取数据字典 */
  const { loadMapInfo, mapLoading } = getLoadMapList([
    `${getTenantID()}${ILoadMapTypeAll.ASSET_TYPE}`, //资产类型
    `${getTenantID()}${ILoadMapTypeAll.AVERAGE_LIFE_METHOD}`, //折旧方式
    `${getTenantID()}${ILoadMapTypeAll.ASSET_SOURCE_TYPE}`, //资产来源
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_BRAND}`, //资产品牌
    `${getTenantID()}${ILoadMapTypeAll.ASSET_AREA}`, //资产存放地点
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_MIDI}`, //量化单位
  ]);

  const [changeFromRef] = Form.useForm(); // 表单实例

  // 年限到期
  const [isMaturity, setIsMaturity] = useState<boolean>(true);
  const [isRequireReson, setIsRequireReson] = useState<boolean>(false);

  /** 获取组织机构树接口 */
  const { getFlowOrgTreeRun, getFlowOrgTreeLoading, getFlowOrgList } = getFlowOrgTreeByOrgIDService();

  /** 获取当前部门用户数据 */
  const { getUserRun, getUserLoading, getUserList } = getUserDataList((res: any) => {
    if (!(res && res?.msgFlag)) {
      message.error(res?.msg);
    }
  });

  useEffect(() => {
    /** 初始化请求组织机构 */
    // let payload = {
    //   params: '0',
    //   flowType: '0',
    // };
    // getFlowOrgTreeRun(payload);
    if (infoObj?.id) {
      // if (infoObj?.claimType === '0') {
      //   setIsRequireReson(false);
      // } else {
      //   setIsRequireReson(true);
      // }
      if (infoObj?.repealType === '0') {
        setIsMaturity(true);
      } else {
        setIsMaturity(false);
      }
      // if (infoObj?.repealType === '0') {
      //   setIsMaturity(true);
      // } else {
      //   setIsMaturity(false);
      // }
      // getUserRun({
      //   //获取当前部门用户信息
      //   userDepartmentID: infoObj?.useDepartmentID,
      // });
      BasicMethods?.setFieldsValue({
        ...infoObj,
        createTime: moment(infoObj?.createTime),
        // expectSum: formatDecimal(infoObj?.expectSum),
      });
      ReMethods?.setFieldsValue({
        ...infoObj,
        createTime: moment(infoObj?.createTime),
        // expectSum: formatDecimal(infoObj?.expectSum),
      });
    }
  }, [infoObj]);

  // 表格表单配置信息
  const [config, BasicMethods] = useDescriptionsType({
    labelWidth: 200,
    basicForm: changeFromRef,

    schemas: [
      {
        key: 'accept-basic',
        title: '',
        fieldChildren: [
          {
            field: `createTime`,
            label: `申请日期`,
            component: 'Render',
            disabled: true,
            required: false,
            placeholder: '自动带出',
            render: (text: string) => {
              return <span>{removeDateHmsStr(text)}</span>;
            },
          },
          {
            field: `applyCode`,
            label: `流水单号`,
            component: 'Input',
            disabled: true,
            placeholder: '自动带出',
            required: false,
          },
          {
            field: `createrName`,
            label: `申请人`,
            component: 'Input',
            disabled: true,
            required: false,
            placeholder: '自动带出',
          },
          {
            field: `createPhone`,
            label: `联系电话`,
            component: 'Input',
            disabled: true,
            required: false,
            placeholder: '自动带出',
          },
          {
            field: `createDepartmentName`,
            label: `申请部门/单位`,
            component: 'Input',
            disabled: true,
            required: false,
            placeholder: '自动带出',
          },
          {
            field: `createPositionName`,
            label: `职务岗位`,
            component: 'Input',
            disabled: true,
            required: false,
            placeholder: '自动带出',
          },
        ],
      },
    ],
  });

  // 表格表单配置信息
  const [ReConfig, ReMethods] = useDescriptionsType({
    labelWidth: 200,
    basicForm: changeFromRef,

    schemas: [
      {
        key: 'accept-basic',
        title: '',
        fieldChildren: [
          {
            field: `applyTitle`,
            label: `事项名称`,
            component: 'Input',
            disabled: true,
            placeholder: '自动带出',
            required: false,
            autoComplete: 'off',
            colSpan: 0,
          },
          {
            field: 'repealType',
            label: `报废类别`,
            component: 'Render',
            disabled: true,
            placeholder: '自动带出',
            colSpan: 2,
            render: (text) => {
              return (
                <span>{repealTypeList.find((item) => item.value == text)?.name || '--'}</span>
                // <Select
                //   onChange={(_value, node) => {}}
                //   options={repealTypeList}
                //   loading={false}
                //   disabled={true}
                //   placeholder="请选择"
                //   fieldNames={{
                //     label: 'label',
                //     value: 'value',
                //   }}
                //   showSearch={true}
                // />
              );
            },
          },
          {
            field: `damageType`,
            label: `损坏类型`,
            component: 'Render',
            disabled: true,
            placeholder: '自动带出',
            ishidden: isMaturity,
            render: (text) => {
              return <span>{damageTypeList.find((item) => item.value == text)?.name || '--'}</span>;
            },
          },
          {
            field: `riskLevel`,
            label: `风险程度`,
            component: 'Render',
            disabled: true,
            placeholder: '自动带出',
            colSpan: isMaturity ? 2 : 1,
            render: (text) => {
              return <span>{riskLevelList.find((item) => item.value == text)?.name || '--'}</span>;
            },
          },
          {
            field: `claimType`,
            label: `索赔类型`,
            colSpan: 2,
            component: 'Render',
            disabled: true,
            placeholder: '自动带出',
            ishidden: isMaturity,
            render: (text) => {
              return <span>{claimTypeList.find((item) => item.value == text)?.name || '--'}</span>;
            },
          },
          {
            field: `claimReason`,
            label: `索赔原因`,
            component: 'InputTextArea',
            disabled: true,
            placeholder: '自动带出',
            ishidden: infoObj?.claimType === '0' || isMaturity,
            colSpan: 2,
            allowClear: true,
            showCount: true,
            maxLength: 200,
            autoSize: { minRows: 2, maxRows: 4 },
          },
          {
            field: `applyInfo`,
            label: `申请理由`,
            component: 'InputTextArea',
            disabled: true,
            placeholder: '自动带出',
            required: false,
            colSpan: 2,
            allowClear: true,
            showCount: true,
            maxLength: 200,
            autoSize: { minRows: 2, maxRows: 4 },
          },
          {
            field: `applyFile`,
            label: `相关附件`,
            component: 'Render',
            required: false,
            placeholder: '请上传',
            render: (text, record) => {
              const fileName = 'applyFile';
              return (
                <div
                  style={{
                    height: '100%',
                    display: 'flex',
                    alignItems: 'center',
                    marginLeft: '8px',
                  }}
                >
                  {record?.[fileName]
                    ? splitFileUrl(record?.[fileName])?.map((e, i) => {
                        return (
                          <div>
                            <Tooltip title={e.attachName} key={new Date().getTime() * 25615265152 + e?.attachName}>
                              <a
                                onClick={() => {
                                  message.success('下载中，请稍后...');
                                  downloadTemplate('/assetInfo/downloadFile', e?.attachName, e?.attachUrl, () => {});
                                }}
                              >
                                <MyIcon type="icon-file-text-fill" />
                                &nbsp;
                                {getFileNameNotType(e.attachName, 8)}
                              </a>
                            </Tooltip>
                            {/* 轻阅读预览 */}
                            <Tooltip title={'在线预览'}>
                              <Button type="link" size="small" onClick={() => onOpenReadOfdWord(e?.attachUrl)} icon={<EyeOutlined />} />
                            </Tooltip>
                          </div>
                        );
                      })
                    : '--'}
                </div>
              );
            },
          },
        ],
      },
    ],
  });

  return (
    <>
      <div className="commonTabsBodyDom">
        <div className={Cls('tabsBodyInfoDom', `${styleFixCls}updateFormBox`)}>
          <ScrollBarLayout style={{ padding: '20px 10%' }}>
            <Spin spinning={getUserLoading || mapLoading}>
              <TypographyTitle children={'资产报废申请'} style={{ textAlign: 'center', borderLeft: 'none' }} level={1} />
              <TypographyTitle children={'基本信息'} style={{ margin: '25px 0px 20px' }} level={2} />
              <DescriptionsType config={config} />

              <TypographyTitle children={'资产报废信息'} style={{ margin: '25px 0px 20px' }} level={2} />
              <DescriptionsType config={ReConfig} />
              {/* 列表数据 */}
              <TypographyTitle children={'资产详单'} style={{ margin: '25px 0px 20px' }} level={2} />
              <DetailInfoTableList dataList={infoObj?.massetApplyNumberList || []} />
            </Spin>
          </ScrollBarLayout>
        </div>
      </div>
    </>
  );
};

// schemas: [
//   {
//     field: `createTime`,
//     label: `申请日期`,
//     component: 'Render',
//     disabled: true,
//     required: false,
//     placeholder: '自动带出',
//     render: (text: string) => {
//       return <span>{removeDateHmsStr(text)}</span>;
//     },
//   },
//   {
//     field: `applyCode`,
//     label: `流水单号`,
//     component: 'Input',
//     disabled: true,
//     placeholder: '自动带出',
//     required: false,
//   },
//   {
//     field: `createrName`,
//     label: `申请人`,
//     component: 'Input',
//     disabled: true,
//     required: false,
//     placeholder: '自动带出',
//   },
//   {
//     field: `createPhone`,
//     label: `联系电话`,
//     component: 'Input',
//     disabled: true,
//     required: false,
//     placeholder: '自动带出',
//   },
//   {
//     field: `createDepartmentName`,
//     label: `申请部门/单位`,
//     component: 'Input',
//     disabled: true,
//     required: false,
//     placeholder: '自动带出',
//   },
//   {
//     field: `createPositionName`,
//     label: `职务岗位`,
//     component: 'Input',
//     disabled: true,
//     required: false,
//     placeholder: '自动带出',
//   },
//   {
//     field: `applyTitle`,
//     label: `事项名称`,
//     component: 'Input',
//     disabled: true,
//     placeholder: '自动带出',
//     required: false,
//     autoComplete: 'off',
//   },
//   {
//     field: 'repealType',
//     label: `报废类别`,
//     component: 'Render',
//     disabled: true,
//     placeholder: '自动带出',
//     render: (text) => {
//       return (
//         <span>{repealTypeList.find((item) => item.value == text)?.name || '--'}</span>
//         // <Select
//         //   onChange={(_value, node) => {}}
//         //   options={repealTypeList}
//         //   loading={false}
//         //   disabled={true}
//         //   placeholder="请选择"
//         //   fieldNames={{
//         //     label: 'label',
//         //     value: 'value',
//         //   }}
//         //   showSearch={true}
//         // />
//       );
//     },
//   },
//   {
//     field: `damageType`,
//     label: `损坏类型`,
//     component: 'Render',
//     disabled: true,
//     placeholder: '自动带出',
//     ishidden: isMaturity,
//     render: (text) => {
//       return <span>{damageTypeList.find((item) => item.value == text)?.name || '--'}</span>;
//     },
//   },
//   {
//     field: `riskLevel`,
//     label: `风险程度`,
//     component: 'Render',
//     disabled: true,
//     placeholder: '自动带出',
//     colSpan: isMaturity ? 2 : 1,
//     render: (text) => {
//       return <span>{riskLevelList.find((item) => item.value == text)?.name || '--'}</span>;
//     },
//   },
//   {
//     field: `claimType`,
//     label: `索赔类型`,
//     colSpan: 2,
//     component: 'Render',
//     disabled: true,
//     placeholder: '自动带出',
//     ishidden: isMaturity,
//     render: (text) => {
//       return <span>{claimTypeList.find((item) => item.value == text)?.name || '--'}</span>;
//     },
//   },
//   {
//     field: `claimReason`,
//     label: `索赔原因`,
//     component: 'InputTextArea',
//     disabled: true,
//     placeholder: '自动带出',
//     ishidden: infoObj?.claimType === '0' || isMaturity,
//     colSpan: 2,
//     allowClear: true,
//     showCount: true,
//     maxLength: 200,
//     autoSize: { minRows: 2, maxRows: 4 },
//   },
//   {
//     field: `applyInfo`,
//     label: `申请理由`,
//     component: 'InputTextArea',
//     disabled: true,
//     placeholder: '自动带出',
//     required: false,
//     colSpan: 2,
//     allowClear: true,
//     showCount: true,
//     maxLength: 200,
//     autoSize: { minRows: 2, maxRows: 4 },
//   },
//   {
//     field: `applyFile`,
//     label: `相关附件`,
//     component: 'Render',
//     required: false,
//     placeholder: '请上传',
//     render: (text, record) => {
//       const fileName = 'applyFile';
//       return (
//         <div
//           style={{
//             height: '100%',
//             display: 'flex',
//             alignItems: 'center',
//             marginLeft: '8px',
//           }}
//         >
//           {record?.[fileName]
//             ? splitFileUrl(record?.[fileName])?.map((e, i) => {
//               return (
//                 <Tooltip title={e.attachName} key={new Date().getTime() * 25615265152 + e?.attachName}>
//                   <a
//                     onClick={() => {
//                       message.success('下载中，请稍后...');
//                       downloadTemplate('/assetInfo/downloadFile', e?.attachName, e?.attachUrl, () => { });
//                     }}
//                   >
//                     <MyIcon type="icon-file-text-fill" />
//                     &nbsp;
//                     {getFileNameNotType(e.attachName, 8)}
//                   </a>
//                 </Tooltip>
//               );
//             })
//             : '--'}
//         </div>
//       );
//     },
//   },
// ],
